$(document).ready(function(){
	calculateSubAccTotal();
	
	$("#fileUploadContainer").dialog( {
		bgiframe :true,
		autoOpen :false,
		autoOpen :false,
		width: 500,
		modal :true,
		buttons : {
			"Cancel": function() {
				$(this).dialog('close');
			},
			"Upload" : function() {
				readStatement();
				$(this).dialog('close');
			}
		}
	});
	
	$("#uploadBtn").click(function(){
		$("#fileUploadContainer").dialog("open");
	});
	
	initializeDisplay();
	
});


var run = false;

function initializeDisplay(){
	$(".date").attr("width", "15%");
	$(".rf").attr("width", "3%");
	$(".balance").attr("width", "13%");
	$(".income").attr("width", "13%");
	$(".expense").attr("width", "13%");
}

function toggleCategoryBalances(){
	
	$(".category").toggle(function(){
		if ($("#toggleZeroAccountCheckBox").is(":checked")){
			$(".zeroCat").hide();
		} else {
			$(".zeroCat").show();
		}
	});;
	
}

function readStatement(){
	var url="/index.php?mod=uploadSavingsStatement";
	var parms = new Object();
	parms["action"]= "uploadStatement";

	$.post(url,parms,function(resultData){
		var errorCode = $(resultData).find("code").text();
		if(errorCode == 0){
			top.location = "index.php?mod=savingsView&accId=2";
		} else if(errorCode == 1) {
			$("#msgDlg").html("There was a database error. Askies.");
			$("#msgDlg").dialog("open");
		}
	});
	
	
	$("#fileUploadForm").find("#action").val($("#accountId").val());
	$("#accId").val($("#accountId").val());
	$("#fileUploadForm").ajaxSubmit({
			success: function(resultData) { 
				var errorCode = $(resultData).find("code").text();
				
				if(errorCode == 0){
					top.location = "index.php?mod=savingsView&accId=2";
				} else {
					alert($(resultData).find("errMessage").text());
				} 
		    } 
	}); 
}

function doReconcile(){
	var parms = new Object();
	var url="/index.php?mod=controller1";
	parms["action"] = "doSavingsReconcile";
	parms["accId"] = $("#accountId").val();
	parms["mainTransId"] = $("#currentMainTransaction").val();
	parms["reconTransDescription"]= $("#reconDescription").val();
	parms["transId"]="";
	parms["newTransDate"]="";
	parms["newTransDescription"]="";
	parms["newTransAmount"]="";
	parms["newTransBudgetItemId"]="";
	
	$(".reconCheckbox:checked").each(function(){
		if ($(this).parent().parent().attr("id") != ""){
			parms["transId"] += "," + $(this).parent().parent().attr("id");
		} else if ($(this).parent().parent().attr("id") == ""){
			parms["newTransDate"] += ","+$(this).parent().parent().find(".transDate").find("input").val();
			parms["newTransDescription"] += ","+ ($(this).parent().parent().find(".reconDescription").find(".textInput").val() == "" ? $(this).parent().parent().find(".transDescription").find("select").val() : $(this).parent().parent().find(".reconDescription").find(".textInput").val());
			
			var budgetItemId = $(this).parent().parent().find(".transDescription").find("select option:selected").attr("id");
			
			//This is to cater for filler transactions
			if (budgetItemId == null){
				budgetItemId = "filler";
			}
			
			parms["newTransBudgetItemId"] += ","+budgetItemId;
			
			if ($(this).parent().parent().find(".expenseAmount").find("input").val() != ""){
				var amount = $(this).parent().parent().find(".expenseAmount").find("input").val();
				//if this is a filler transaction we must not change the sign
				if ($(this).parent().parent().find(".reconDescription").find(".textInput").val() != "Filler"){
					amount = eval(amount) * -1;
				}	
				parms["newTransAmount"] += ","+amount;
			} else if ($(this).parent().parent().find(".incomeAmount").find("input").val() != "") {
				var amount = $(this).parent().parent().find(".incomeAmount").find("input").val();
				//we trim away the minus for filler transactions
				amount = eval(amount.replace("-", ""));
				parms["newTransAmount"] += ","+amount;
			}
		}
	});
	
	$.post(url,parms,function(resultData){
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			closeTransWindow();
			top.location = "index.php?mod=savingsView&accId=" + $("#accountId").val();
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function showCreateTransContainer(){
	var rowStr = '<tr class="reconTrans">'
					+ '<td class="transDate"><input type="text" class="currency savTransDate"/></td>'
					+ '<td class="transDescription">'+ getCatDropdown() +'</td>'
					+ '<td class="reconDescription"><input class="textInput" type="text" style="width: 120px;"/></td>'
					+ '<td><input class="reconCheckbox" type="checkbox" value="false" onchange="newTransCheckboxChange(this);"/></td>'
					+ '<td class="expenseAmount"><input type="text" class="shortest" onblur="updateInput();" style="width: 60px;"/></td>'
					+ '<td class="incomeAmount"><input type="text" class="shortest" onblur="updateInput();" style="width: 60px;"/></td>'
					+ '<td>R 0</td></tr>';
	var lastElem = $(".reconTrans").last();
	if ($(lastElem).attr("id") == null){
		$(rowStr).insertAfter($(".transHeaderRow"));
	} else {
		$(rowStr).insertAfter(lastElem);
	}
	getCatDropdown();
	
	$(".savTransDate").datepicker({ dateFormat: 'yy-mm-dd' }); 
	$(".savTransDate").val(new Date().formatDate("yyyy-MM-dd"));
}

function newTransCheckboxChange(input){
	var sum = 0;
	var inputValue = 0;
	
	disableNonCorrespondingCheckbox();
	
	$(".reconCheckbox:checked").each(function(){
		var html = $(this).parent().parent().find(".transmount").html();
		var val = $(this).parent().parent().find(".transmount").val();
		if (html != ""){
			inputValue = eval(html);
		} else {
			inputValue = eval(val);
		}
		sum += inputValue;
	});
	$("#selectedAmount").html("R "+sum.toFixed(2));
	
	
	var difference = (eval($("tr[id='"+$("#currentMainTransaction").val()+"']").find(".mainTransAmount").html()) - sum);
	$("#reconDiffAmount").html("R "+ difference.toFixed(2));
	
	if (difference == 0){
		$("#reconBtn").removeAttr("disabled");
	} else {
		$("#reconBtn").attr("disabled", "true");
	}
}

function disableNonCorrespondingCheckbox(){
	
	
	if ($(".reconCheckbox:checked").parent().parent().find(".transmount").parent().hasClass("expenseAmount")){
		$(".reconTrans").each(function(){
			if ($(this).find(".transmount").parent().hasClass("incomeAmount")){
				$(this).find(".reconCheckbox").attr("disabled", "disabled");
			} else if ($(this).find(".transmount").parent().hasClass("expenseAmount")) {
				$(this).find(".reconCheckbox").removeAttr("disabled");
			}
		});
	} else if ($(".reconCheckbox:checked").parent().parent().find(".transmount").parent().hasClass("incomeAmount")){ 
		$(".reconTrans").each(function(){
			if ($(this).find(".transmount").parent().hasClass("expenseAmount")){
				$(this).find(".reconCheckbox").attr("disabled", "disabled");
			} else {
				$(this).find(".reconCheckbox").removeAttr("disabled");
			}
		});
	} else {
		$(".reconTrans").each(function(){
			$(this).find(".reconCheckbox").removeAttr("disabled");
		});
	}
}

function updateInput(){
	$(".shortest").each(function(){
		if ($(this).val() != ""){
			$(this).addClass("transmount");
		} else {
			$(this).removeClass("transmount");
		}
	});
}

function toggleZeroAccounts(){
	$(".zeroCat").toggle();
}

function getCatDropdown(){
	var catStr = "<select id='category'>";
	$(".category").each(function(){
		catStr += "<option id='"+ $(this).find("a").attr("id") +"'>"+ $(this).find("a").html() +"</option>";
	});
	catStr += "</select>";
	return catStr;
}

function showContainer(){
	$("#demoContainer").dialog({
		bgiframe :true,
		autoOpen :false,
		width: 650,
		maxHeight: 200,
		modal :true
	});
	$("#demoContainer").dialog("open");
}

function closeTransWindow(){
	$("#transDate").datepicker('destroy');
	$("#demoContainer").dialog("destroy");
}

function createFillerTransaction(){
	$('<tr class="reconTrans"><td class="transDate"><input type="text" class="currency savTransDate hasDatepicker" disabled></td><td class="transDescription"><input type="text" value="Filler" disabled/></td><td class="reconDescription"><input type="text" style="width: 120px;" class="textInput" value="Filler" disabled/></td><td><input type="checkbox" onchange="newTransCheckboxChange(this);" value="false" class="reconCheckbox"></td><td class="expenseAmount"><input type="text" style="width: 60px;" onblur="updateInput();" class="shortest"></td><td class="incomeAmount"><input type="text" style="width: 60px;" onblur="updateInput();" class="shortest"></td><td>R 0</td></tr>').insertAfter($(".reconTrans:last"));
	$(".hasDatepicker:last").val($.datepicker.formatDate('yy-mm-dd', new Date()));
}

function getAccountDetails(a){
	$(".reconTrans").remove();
	$("#currentMainTransaction").val($(a).parent().parent().attr("id"));
	$(".transactions").each(function(){
		$(this).clone().removeClass("transactions").addClass("reconTrans").insertAfter(".transHeaderRow");
	});
	
	$(".reconTrans").each(function(){
		$("<td class='reconDescription'><input class='textInput' style='width: 120px' type='text' value='"+ $(this).find(".transDescription").html() +"'/></td>").insertAfter($(this).find(".transDescription"));
	});
	
	$("#reconAmount").html("R "+ $(a).parent().parent().find(".mainTransAmount").html());
	
	
	$(".reconTrans").find("input:checkbox").removeAttr("disabled").change(function(){
		
		disableNonCorrespondingCheckbox();
		
		var sum = 0;
		$(".reconCheckbox:checked").each(function(){
			if ($(this).parent().parent().find(".transmount").html() != "")
				sum += eval ($(this).parent().parent().find(".transmount").html());
			else
				sum += eval ($(this).parent().parent().find(".transmount").val());
		});
		$("#selectedAmount").html("R "+sum.toFixed(2));
		var difference = ($(a).parent().parent().find(".mainTransAmount").html() - sum);
		$("#reconDiffAmount").html("R "+ difference.toFixed(2));
		
		if (Math.abs(difference.toFixed(2)) == 0){
			$("#reconBtn").removeAttr("disabled");
		} else {
			$("#reconBtn").attr("disabled", "true");
		}
	});
		showContainer();
}

function calculateSubAccTotal(){
	var total = 0;
	$(".subAccTotal").each(function(){
		if ($(this).html() != ""){
			total += eval($(this).html());
			$(this).parent().html("R "+formatCurrency(eval($(this).html())));
		}
	});
	$("#savingsTotal").html(formatCurrency(total.toFixed(2)));
}

function updateTransaction(link){
	$("#currentSubAccount").val($(link).attr("id"));
	
	var parms = new Object();
	var url="/index.php?mod=controller1";
	parms["action"] = "getSavingsTransactions";
	parms["categoryId"] = 4;
	parms["budgetItemId"] = $(link).attr("id");
	parms["accountId"] = $("#accountId").val();
	
	var budgetItemDesc = $(link).html();

	$.post(url,parms,function(resultData){
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			displayTransactions(resultData, budgetItemDesc);
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function getAmountValue(amount, income){
	if (amount == ""){
		return "";
	}
	var value = eval(amount);
	if (income){
		if (value < 0) 
			return "";
		else
		 return value;
	} else {
		if (value < 0)
			return value * -1;
		else
			return "";
	}
}

function getSavingsSubAccounts(){
	var parms = new Object();
	var url="/index.php?mod=controller1";
	parms["action"] = "getSavingsSubAccounts";

	$.post(url,parms,function(resultData){
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			displaySavingsSubAccounts(resultData);
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function tranferFunds(){
	var parms = new Object();
	var url="/index.php?mod=controller1";
	parms["action"] = "transferFunds";
	parms["amount"] = $("#transferAmount").val();
	parms["fromSubAccId"] = $("#transferFromAccount").val();
	parms["toSubAccId"] = $("#transferToAccount").val();
	parms["fromSubAccDesc"] = $("#transferFromAccount option:selected").text(); 
	parms["toSubAccDesc"] = $("#transferToAccount option:selected").text();


	$.post(url,parms,function(resultData){
		var errorCode = $(resultData).find("code").text();
		if (errorCode == 0) {
			location.reload();
		} else {
			alert($(resultData).find("errMessage").text());
		}
	});
}

function displaySavingsSubAccounts(data){
	$(".subAcc").remove();
	$(data).find("SubAccount").each(function(){
		$("#transferFromAccount").append("<option class='subAcc' value='"+ $(this).find("budgetitemid").text() +"'>"+ $(this).find("description").text() +"</option>");
		$("#transferToAccount").append("<option class='subAcc' value='"+ $(this).find("budgetitemid").text() +"'>"+ $(this).find("description").text() +"</option>");
	});
	$("#transferFromAccount").val($("#currentSubAccount").val());
}

function displayTransferDialog(){
	$("#fundsTransferDiv").dialog( {
		bgiframe :true,
		autoOpen :false,
		width: 420,
		title:"Transfer Funds",
		maxHeight: 200,
		modal :true,
		buttons : {
			Cancel : function() {
				$(this).dialog('destroy');
			},
			Submit : function() {
				tranferFunds();
				$(this).dialog('destroy');
			}	
		}
	});
	getSavingsSubAccounts();
	$("#fundsTransferDiv").dialog("open");
	$("#transferAmount").focus();
}

function displayTransactions(resultData, budgetItemDesc){
	$("#transactionsView").attr("title", budgetItemDesc);
	
	$("#transactionsView").dialog( {
		bgiframe :true,
		autoOpen :false,
		width: 550,
		maxHeight: 200,
		modal :true,
		buttons : {
			Ok : function() {
				$("#transDate").datepicker('destroy');
				$(this).dialog('destroy');
			},
			Transfer : function() {
				//$("#transDate").datepicker('destroy');
				$(this).dialog('destroy');
				displayTransferDialog();
			}	
		}
	});
	
	
	$(".savTransRow").remove();
	$(resultData).find("Transaction").each(function(){
			
		var rowString = "<tr class='savTransRow'><td>"+ $(this).find("date").text() +"</td><td>"+ $(this).find("description").text() +"</td>"
					+"<td>"+ (getAmountValue($(this).find("amount").text(), false) == "" ? "&nbsp;" : ("R "+getAmountValue($(this).find("amount").text(), false))) +"</td>"
					+"<td>"+ (getAmountValue($(this).find("amount").text(), true) == "" ? "&nbsp;" : ("R "+getAmountValue($(this).find("amount").text(), true))) +"</td></tr>";
		
			$(rowString).insertAfter(".savTransHeaderRow");
	});
	$("#transactionsView").dialog("open");
}